// AI助手内容组件 - 公共组件
Vue.component('ai-assistant-content', {
  data() {
    return {
      messages: [
        {
          role: 'assistant',
          content: '你好！我是HRM系统的AI助手，有什么可以帮助你的吗？',
          timestamp: new Date()
        }
      ],
      inputMessage: '',
      loading: false
    };
  },
  methods: {
    async sendMessage() {
      if (!this.inputMessage.trim() || this.loading) {
        return;
      }

      // 添加用户消息
      const userMessage = {
        role: 'user',
        content: this.inputMessage.trim(),
        timestamp: new Date()
      };
      this.messages.push(userMessage);
      const question = this.inputMessage.trim();
      this.inputMessage = '';
      this.loading = true;

      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });

      try {
        // 构建历史对话（排除初始欢迎消息）
        const history = this.messages
          .filter(msg => msg.role !== 'assistant' || msg.content !== '你好！我是HRM系统的AI助手，有什么可以帮助你的吗？')
          .slice(0, -1) // 排除当前用户消息
          .map(msg => [msg.role, msg.content]);
        
        // 调用AI API，传递历史对话
        const response = await aiAPI.sendMessage(question, history);
        
        // 添加AI回复
        const aiMessage = {
          role: 'assistant',
          content: response.data.reply || '抱歉，我暂时无法回答这个问题。',
          timestamp: new Date()
        };
        this.messages.push(aiMessage);
      } catch (error) {
        console.error('AI助手错误:', error);
        this.messages.push({
          role: 'assistant',
          content: '抱歉，我遇到了一些问题，请稍后再试。',
          timestamp: new Date()
        });
      } finally {
        this.loading = false;
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },

    scrollToBottom() {
      const container = this.$refs.messageContainer;
      if (container) {
        container.scrollTop = container.scrollHeight;
      }
    },

    clearSession() {
      this.$confirm('确定要清除所有对话记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 重置消息列表为初始状态
        this.messages = [
          {
            role: 'assistant',
            content: '你好！我是HRM系统的AI助手，有什么可以帮助你的吗？',
            timestamp: new Date()
          }
        ];
        this.$message.success('会话已清除');
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }).catch(() => {
        // 用户取消操作
      });
    },

    formatTime(timestamp) {
      const date = new Date(timestamp);
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    }
  },
  template: `
    <div>
      <!-- 卡片容器 -->
      <el-card shadow="hover" style="margin-bottom: 20px;">
        <div slot="header" style="display: flex; align-items: center; justify-content: space-between;">
          <span style="font-size: 18px; font-weight: bold;">
            <i class="el-icon-chat-line-round" style="margin-right: 8px;"></i>
            AI助手
          </span>
        </div>
        
        <!-- 消息列表 -->
        <div 
          ref="messageContainer"
          style="overflow-y: auto; overflow-x: hidden; padding: 15px; background: #f9fafb; border-radius: 4px; height: 500px; margin-bottom: 15px;"
        >
          <div v-for="(message, index) in messages" :key="index" style="margin-bottom: 15px;">
            <div v-if="message.role === 'user'" style="display: flex; justify-content: flex-end;">
              <div style="max-width: 65%; background: #409eff; color: white; padding: 10px 14px; border-radius: 8px; word-wrap: break-word; white-space: pre-wrap;">
                <div>{{ message.content }}</div>
                <div style="font-size: 11px; opacity: 0.8; text-align: right; margin-top: 5px;">{{ formatTime(message.timestamp) }}</div>
              </div>
            </div>
            <div v-else style="display: flex; justify-content: flex-start;">
              <div style="max-width: 65%; background: white; color: #303133; padding: 10px 14px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); word-wrap: break-word; white-space: pre-wrap;">
                <div>{{ message.content }}</div>
                <div style="font-size: 11px; color: #909399; text-align: right; margin-top: 5px;">{{ formatTime(message.timestamp) }}</div>
              </div>
            </div>
          </div>
          <div v-if="loading" style="display: flex; justify-content: flex-start;">
            <div style="background: white; padding: 10px 14px; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
              <i class="el-icon-loading" style="animation: rotating 1s linear infinite;"></i>
              <span style="margin-left: 8px; color: #909399;">正在思考...</span>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div style="display: flex; gap: 10px; align-items: flex-end;">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="2"
            placeholder="请输入您的问题..."
            @keydown.ctrl.enter.native="sendMessage"
            @keydown.meta.enter.native="sendMessage"
            style="flex: 1;"
          ></el-input>
          <div style="display: flex; gap: 5px; align-items: center;">
            <el-button 
              type="primary" 
              @click="sendMessage" 
              :loading="loading"
              :disabled="!inputMessage.trim()"
              icon="el-icon-position"
            >
              发送
            </el-button>
            <el-tooltip content="清除会话" placement="top">
              <el-button 
                icon="el-icon-delete" 
                @click="clearSession"
                :disabled="messages.length <= 1"
                type="text"
                style="font-size: 18px; padding: 9px;"
              ></el-button>
            </el-tooltip>
          </div>
        </div>
        <div style="font-size: 12px; color: #909399; margin-top: 8px; text-align: right;">
          提示：Ctrl + Enter 快速发送
        </div>
      </el-card>
    </div>
  `,
  mounted() {
    // 初始滚动到底部
    this.$nextTick(() => {
      this.scrollToBottom();
    });
  }
});

// 添加旋转动画样式
if (!document.getElementById('ai-assistant-style')) {
  const style = document.createElement('style');
  style.id = 'ai-assistant-style';
  style.textContent = `
    @keyframes rotating {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
  `;
  document.head.appendChild(style);
}
